package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 登录认证和授权
 * @author ：zengjie
 * @date ：2020/11/15
 */
@Component
public class MyLoginSecurity implements UserDetailsService {
    @Reference
    private UserService userService;

    /**
     * 登录验证和授权
     * @param username 用户输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       User user = userService.findUserByUsername(username);
       if(user == null) {
           return null;
       }
        String password = user.getPassword();

        List<GrantedAuthority> list = new ArrayList<>();

        Set<Role> roles = user.getRoles();
        //判断角色是否为空
        if (roles != null) {
            for (Role role : roles) {
                //获取角色标识,存入list
                String roleKeyword = role.getKeyword();
                list.add(new SimpleGrantedAuthority(roleKeyword));
                //获取权限列表
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null){
                    for (Permission permission : permissions) {
                        //存入list
                        String permissionkeyword = permission.getKeyword();
                        list.add(new SimpleGrantedAuthority(permissionkeyword));
                    }
                }
            }
        }
        return new org.springframework.security.core.userdetails.User(username,password,list);
    }
}
